﻿using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Auktionshuset
{
    public partial class RegisterWindow
    {
        private string _error;

        public RegisterWindow()
        {
            InitializeComponent();
        }

        public RegisterWindow(string username, string password) : this()
        {
            UsernameTextBox.Text = username;
            PasswordTextBox.Password = password;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            if (TosCheckBox.IsChecked == false)
            {
                StatusTextBlock.Text = "You need to accept the terms of service.";
            }
            else if (UsernameTextBox.Text.Length < 4)
            {
                StatusTextBlock.Text = "Your username needs to be atleast 4 characters long";
            }
            else if (PasswordTextBox.Password.Length < 6)
            {
                StatusTextBlock.Text = "Your password needs to be atleast 6 characters long";
            }
            else if (AliasTextBox.Text.Length < 4)
            {
                StatusTextBlock.Text = "Your alias needs to be atleast 4 characters long";
            }
            else
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += worker_DoWork;
                worker.RunWorkerCompleted += worker_RunWorkerCompleted;

                LoaderGrid.Visibility = Visibility.Visible;
                worker.RunWorkerAsync(new string[] {UsernameTextBox.Text, PasswordTextBox.Password, AliasTextBox.Text});
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] arguments = (string[])e.Argument;

            string username = arguments[0];
            string password = arguments[1];
            string alias = arguments[2];

            _error = null;

            EndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 40404);
            try
            {
                Socket socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ep);

                Connection conn = new Connection(socket);
                Response resp = conn.AttemptRegister(username, password, alias);
                if (!resp.Success)
                {
                    _error = resp.Error;
                }

                // We're done with this connection, let's close it
                conn.Close();
            }
            catch (SocketException exception)
            {
                _error = exception.Message;
            }

            // Next up: worker_RunWorkerCompleted
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LoaderGrid.Visibility = Visibility.Hidden;
            if (_error == null)
            {
                DialogResult = true;
                Close();
            }
            else
            {
                StatusTextBlock.Text = _error;
            }
        }

        private void TermsOfService_OnClick(object sender, RoutedEventArgs e)
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Auktionshuset.tos.html"))
            {
                if (stream != null)
                {
                    var browser = new WebBrowser();
                    browser.NavigateToStream(stream);

                    var window = new Window
                    {
                        Owner = this,
                        WindowStartupLocation = WindowStartupLocation.CenterOwner,
                        ShowInTaskbar = false,
                        Width = 640,
                        Height = 480,
                        Title = "Terms of Service",
                        Content = browser
                    };

                    window.ShowDialog();
                }
            }
        }

        private void Form_OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                SubmitButton_Click(sender, e);
            }
        }
    }
}
